import axios, { InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { ElLoading } from "element-plus";
import { ElMessage } from "element-plus";
import router from "../router";
import store from "../store";

axios.defaults.baseURL = "/yihu";

declare module "axios" {
  interface AxiosResponse<T = any> {
    message: string;
    code: number;
    // 这里追加你的参数
  }
  export function create(config?: AxiosRequestConfig): AxiosInstance;
}

let loading: any;
const startLoading = () => {
  interface Options {
    lock: boolean;
    text: string;
    background: string;
  }
  const options: Options = {
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  };
  loading = ElLoading.service(options);
};
const endLoading = () => {
  loading.close();
};

// 请求拦截
axios.interceptors.request.use((config: InternalAxiosRequestConfig<any>) => {
  // 开始Loading
  startLoading();
  const token = window.localStorage.getItem("token");  
  if (token) {
    config.headers.token = token;
  }
  return config;
});
// 响应拦截
axios.interceptors.response.use(
  (res: AxiosResponse<any, any>) => {
    endLoading();
    if (res.status === 200) {
        
      if (res.data.code == 30001) {
        ElMessage({
          message: res.data.message,
          type: "error",
          onClose: () => {
            router.push("/login");
            localStorage.setItem("token","");
            store.dispatch("updateUserInfo", {});
          },
        });
      }
      return res.data;
    }
  },
  (error) => {
    endLoading();
    const { response: res } = error;
    const msg =
      typeof res.data === "string"
        ? res.data
        : res.data.error || "请求失败，请稍后重试";
    ElMessage.error(msg);
    // 错误提醒
    return Promise.reject(error);
  }
);

export default axios;

// let server_url = "192.108";
// let params = {
//   id: 1,
//   name: "张三",
// };
// axios.get(
//   `${server_url} user/center/details?id=${params.id}&name=${params.name}`
// );

// axios.get(
//   server_url + "user/center/details?id" + params.id + "&name=" + params.name
// );

// axios({
//   url: "/login/doLogin",
//   method: "get",
//   params: {
//     id: params.id,
//     name: params.name,
//   },
// });
// axios({
//   url: server_url+"/login/doLogin",
//   method: "get",
//   params: params,
// });
